using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;

/****************************************************
// 功能：技能Button
// | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
// | Copyright (c) 2021-2025 聊来 All rights reserved.
// | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">聊来</a> )
// | @Author: 贯彻己道的云 <18970881148@qq.com>
// | DateTime: 2025/3/27 15:3:8
*****************************************************/

public class SkillItem : BaseWindow
{
    public Image imgCycle;
    public Image skillIcon;
    public Image imgCd;
    public Text txtCd;
    public Image imgPoint;
    public Image imgForbid;
    public Transform effectRoot;


    private int skillIndex;
    private SkillConfig skillConfig;
    private float pointDis;
    private Vector2 startPosition;
    private Coroutine ct = null;

    private HeroView heroView;

    public void InitSkillItem(SkillConfig skillConfig, int skillIndex)
    {
        SetActive(effectRoot, false);
        InitWindows();

        // 获取英雄的显示单位
        heroView = BattleController.Instance.GetSelfHero().mainViewUnit as HeroView;

        this.skillIndex = skillIndex;
        this.skillConfig = skillConfig;

        pointDis = Screen.height * 1.0f / Constants.SCREEN_STANDARD_HEIGHT * Constants.SKILL_OP_DIS;
        if (skillConfig.isNormalAttack  == false)
        {
            SetSprite(skillIcon, "Images/player/" + skillConfig.iconName);
            SetActive(imgCd, false);
            SetActive(txtCd, false);
            
            OnClickDown(skillIcon.gameObject, data =>
            {
                startPosition = data.position;
                SetActive(imgCycle);
                SetActive(imgPoint);
                ShowSkillAtkRange(true);

                // 通知场景中显示skill引导
                switch (skillConfig.releaseMode)
                {
                    case ReleaseModeEnum.Postion:
                        heroView.SetSkillGuide(skillIndex, true, ReleaseModeEnum.Postion, Vector3.zero);
                        break;
                    case ReleaseModeEnum.Direction:
                        heroView.SetSkillGuide(skillIndex, true, ReleaseModeEnum.Direction, Vector3.zero);
                        break;
                    case ReleaseModeEnum.None:
                    case ReleaseModeEnum.Click:
                    default: break;
                }
            });
            
            OnDrag(skillIcon.gameObject, data =>
            {
                var dir = data.position - startPosition;
                var len = dir.magnitude;
                if (len > pointDis)
                {
                    var clampDir = Vector2.ClampMagnitude(dir, pointDis);
                    imgPoint.transform.position = startPosition + clampDir;
                }
                else
                {
                    imgPoint.transform.position = data.position;
                }

                switch (skillConfig.releaseMode)
                {
                    case ReleaseModeEnum.Postion:
                        if (dir == Vector2.zero) { return; }

                        dir = BattleController.Instance.SkillDisMultipler * dir;
                        var clampDir = Vector2.ClampMagnitude(dir, skillConfig.targetCfg.selectRange);
                        var clampDirVector3 = new Vector3(clampDir.x,0, clampDir.y);
                        clampDirVector3 = Quaternion.Euler(0, 45, 0) * clampDirVector3;
                        heroView.SetSkillGuide(skillIndex, true, ReleaseModeEnum.Postion, clampDirVector3);
                        break;
                    case ReleaseModeEnum.Direction:
                        var dirVector3 = new Vector3(dir.x, 0, dir.y);
                        dirVector3 = Quaternion.Euler(0, 45, 0) * dirVector3;
                        heroView.SetSkillGuide(skillIndex, true, ReleaseModeEnum.Direction, dirVector3.normalized);
                        break;
                    case ReleaseModeEnum.None:
                    case ReleaseModeEnum.Click:
                    default: break;
                }

                if (len >= Constants.SKILL_CANCEL_DIS)
                {
                    SetActive(BattleController.Instance.playerWindow.imgCancelSkill);
                }
                else
                {
                    SetActive(BattleController.Instance.playerWindow.imgCancelSkill, false);
                }
            });
            
            OnClickUp(skillIcon.gameObject, data =>
            {
                var dir = data.position - startPosition;
                imgPoint.transform.position = transform.position;
                SetActive(imgCycle, false);
                SetActive(imgPoint, false);
                SetActive(BattleController.Instance.playerWindow.imgCancelSkill, false);
                ShowSkillAtkRange(false);

                if (dir.magnitude >= Constants.SKILL_CANCEL_DIS)
                {
                    heroView.DisableSkillGuide(skillIndex);
                    return;
                }
                
                switch (skillConfig.releaseMode)
                {
                    case ReleaseModeEnum.Click:
                        ClickSkillItem();
                        break;
                    case ReleaseModeEnum.Postion:
                    {
                        dir = BattleController.Instance.SkillDisMultipler * dir;
                        Vector2 clampDir = Vector2.ClampMagnitude(dir, skillConfig.targetCfg.selectRange);
                        heroView.DisableSkillGuide(skillIndex);
                        Vector3 clampDirVector3 = new Vector3(clampDir.x, 0, clampDir.y);
                        clampDirVector3 = Quaternion.Euler(0, 45, 0) * clampDirVector3;
                        ClickSkillItem(clampDirVector3);
                        break;
                    }
                    case ReleaseModeEnum.Direction:
                    {
                        heroView.DisableSkillGuide(skillIndex);
                        if(dir == Vector2.zero) { return; }
                        Vector3 dirVector3 = new Vector3(dir.x, 0, dir.y);
                        dirVector3 = Quaternion.Euler(0, 45, 0) * dirVector3;
                        ClickSkillItem(dirVector3.normalized);
                        break;
                    }
                    case ReleaseModeEnum.None:
                    default:
                        Debug.LogWarning("skill release mode not exist.");
                        break;
                }
                
                ShowEffect();
            });
        }
        else
        {
            // 普通攻击
            OnClickDown(skillIcon.gameObject, data =>
            {
                ShowSkillAtkRange(true);
                ClickSkillItem();
            });
            
            OnClickUp(skillIcon.gameObject, data =>
            {
                ShowEffect();
                ShowSkillAtkRange(false);
            });
        }
    }

    private void ShowEffect()
    {
        if (ct != null)
        {
            StopCoroutine(ct);
            SetActive(effectRoot, false);
        }
        SetActive(effectRoot);
        ct = StartCoroutine(DisableEffect());
    }

    private IEnumerator DisableEffect()
    {
        yield return new WaitForSeconds(0.5f);
        SetActive(effectRoot, false);
    }

    public void ClickSkillItem()
    {
        BattleController.Instance.SendSkillKey(skillConfig.skillId, Vector2.zero);
    }
    
    private void ClickSkillItem(Vector3 vector)
    {
        BattleController.Instance.SendSkillKey(skillConfig.skillId, vector);
    }

    public void SetForbidState(bool state)
    {
        SetActive(imgForbid, state);
    }

    private void ShowSkillAtkRange(bool state)
    {
        if (skillConfig.targetCfg != null)
        {
            heroView.SetAtkSkillRange(state, skillConfig.targetCfg.selectRange);
        }
    }
    
    public bool CheckSkillId(int skillId) {
        return skillConfig.skillId == skillId;
    }

    public void EnterCdState(int cdTime)
    {
        var duration = cdTime / 1000.0f;
        SetActive(imgCd);
        imgCd.fillAmount = 1;
        SetActive(txtCd);
        SetText(txtCd, Mathf.CeilToInt(duration).ToString());
        skillIcon.raycastTarget = false;

        var timer = new MonoTimer(duration)
        {
            OnTimeUpdated = seconds =>
            {
                imgCd.fillAmount = seconds / duration;
                SetText(txtCd, Mathf.CeilToInt(seconds).ToString());
                
            },
            OnTimeCompleted = OnTimeCompleted
        };
        timer.Start();
        
        GameRoot.Instance.AddMonoTimer(timer);
        
    }

    private void OnTimeCompleted()
    {
        SetActive(imgCd, false);
        SetActive(txtCd, false);
        audioManager.PlayUIAudio("com_cd_ok");
        ShowEffect();
        skillIcon.raycastTarget = true;
        
    }

    private void OnDestroy()
    {
        // 解决销毁了PlayerControlWindows之后，CD计时器一直在生效的BUG
        GameRoot.Instance.timerList.Clear();
    }
}
